<?php 
namespace App\Service;

use Exception;
use log;

class SteamUtilService extends BaseService
{
	public static $instance = null;

	public static function getInstance()
	{
		if (self::$instance == null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * toCommunityID(25490879)             // 76561197985756607
	 */
	public function toCommunityID($id)
	{
		if (preg_match('/^STEAM_/', $id)) {
			$parts = explode(':', $id);
			return bcadd(bcadd(bcmul($parts[2], '2'), '76561197960265728'), $parts[1]);
		} elseif (is_numeric($id) && strlen($id) < 16) {
			return bcadd($id, '76561197960265728');
		} else {
			return $id; // We have no idea what this is, so just return it.
		}
	}

	/**
	 * toSteamID(25490879)                 // STEAM_0:1:12745439
	 */
	public function toSteamID($id)
	{
		if (is_numeric($id) && strlen($id) >= 16) {
			$z = bcdiv(bcsub($id, '76561197960265728'), '2');
		} elseif (is_numeric($id)) {
			$z = bcdiv($id, '2'); // Actually new User ID format
		} else {
			return $id; // We have no idea what this is, so just return it.
		}
		$y = bcmod($id, '2');
		return 'STEAM_0:' . $y . ':' . floor($z);
	}

	/**
	 * toUserID(25490879)                  // 25490879
	 */
	public function toUserID($id)
	{
		if (preg_match('/^STEAM_/', $id)) {
			$split = explode(':', $id);
			return $split[2] * 2 + $split[1];
		} elseif (preg_match('/^765/', $id) && strlen($id) > 15) {
			return bcsub($id, '76561197960265728');
		} else {
			return $id; // We have no idea what this is, so just return it.
		}
	}
}